package controllers

import (
	"strconv"
	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web"
)

// LogController 操作日志控制器
type LogController struct {
	web.Controller
}

// ListRequest 日志列表请求参数
type LogListRequest struct {
	Page          int    `json:"page" form:"page"`
	PageSize      int    `json:"pageSize" form:"pageSize"`
	StartTime     int64  `json:"start_time" form:"start_time"`
	EndTime       int64  `json:"end_time" form:"end_time"`
	Username      string `json:"username" form:"username"`
	OperationType string `json:"operation_type" form:"operation_type"`
}

// List 获取操作日志列表
func (c *LogController) List() {
	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	startTime, _ := strconv.ParseInt(c.GetString("start_time"), 10, 64)
	endTime, _ := strconv.ParseInt(c.GetString("end_time"), 10, 64)
	username := c.GetString("username")
	operationType := c.GetString("operation_type")

	// 查询日志列表
	logs, total, err := models.GetOperationLogs(page, pageSize, startTime, endTime, username, operationType)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取操作日志失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取操作日志成功",
		"data": map[string]interface{}{
			"list":  logs,
			"total": total,
			"page":  page,
			"size":  pageSize,
		},
	}
	c.ServeJSON()
}

// GetTypes 获取操作类型列表
func (c *LogController) GetTypes() {
	// 查询操作类型列表
	types, err := models.GetOperationLogTypes()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取操作类型失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取操作类型成功",
		"data":    types,
	}
	c.ServeJSON()
}
